package com.supreme.nettyapp.generalclient.pingclient.schedule;

import com.supreme.nettyapp.generalclient.pingclient.service.PingClientService;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;

@Configuration
@EnableScheduling
@ConditionalOnProperty(prefix = "netty.ping-client", name = "enabled", havingValue = "true")
public class NettySchedule {

    @Resource
    private PingClientService pingClientService;

    @Scheduled(cron = "0/5 * * * * ?")
    public void nettyPingSchedule() {
        MqttFixedHeader fixedHeader = new MqttFixedHeader(
                MqttMessageType.PINGREQ,
                false,
                MqttQoS.AT_MOST_ONCE,
                false,
                0);
        MqttMessage mqttMessage = new MqttMessage(fixedHeader);
        pingClientService.writeAndFlush(mqttMessage);
    }
}
